package com.fingard.dsp.bank.directbank.citic02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.StringUtils;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CITIC02RealTime extends CITIC02Base implements IRealTime {
    private String tmpFifteen ="%-15s";
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req9108);
        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
            if (actItem == null ) {
                tmpRetDetail.respCode = "0";
                tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]批量商户配置信息";
                tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
                tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
                tmpRetDetail.transState = PaymentState.FAIL_Payment;
                tmpRetDetail.payInfoCode = FailCode.E9981;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
            xmlWriter.writeStartElement("ROOT");
            xmlWriter.writeElementString("trancode", "ZLDS001");
            xmlWriter.writeElementString("sndseqno", p_req9108.singleDetail.askNumber);
            xmlWriter.writeElementString("mccprtcno", actItem.appId);
            xmlWriter.writeElementString("mrchname", actItem.userCode);
            xmlWriter.writeElementString("mrchtype", "0401");// 0401	金融服务类-
            xmlWriter.writeElementString("payname", p_req9108.singleDetail.payName);
            xmlWriter.writeElementString("payacc", p_req9108.singleDetail.payAct);
            xmlWriter.writeElementString("phone", p_req9108.singleDetail.cellPhone);
            String accflag = "";
            if(StringUtils.isNotEmpty(p_req9108.singleDetail.sameBnk) && "1".equals(p_req9108.singleDetail.sameBnk)){
                if (p_req9108.singleDetail.isPrivate.equals("1")) {
                    accflag="11";
                } else {
                    accflag="12";
                }
            }else {
                if (p_req9108.singleDetail.isPrivate.equals("1")) {
                    accflag="21";
                } else {
                    accflag="22";
                }
            }
            xmlWriter.writeElementString("accflag", accflag);
            xmlWriter.writeElementString("idtype", convertCertTypeToBank(p_req9108.singleDetail.certType));
            xmlWriter.writeElementString("idno", p_req9108.singleDetail.certNum);
            xmlWriter.writeElementString("amt", p_req9108.singleDetail.payAmount);
            String tfprtcno = p_req9108.singleDetail.sourceNoteCode;
            if (StringHelper.isNullOrEmpty(tfprtcno)) {
                tfprtcno = p_req9108.singleDetail.abstractATS;
            }
            xmlWriter.writeElementString("tfprtcno", tfprtcno);
            xmlWriter.writeElementString("protocolno", p_req9108.singleDetail.authCode);
            xmlWriter.writeEndElement();
            StringBuilder sbContent=new StringBuilder();
            //报文长度（8）+地区码（4）+业务种类（6）+委托单位（15）+业务单位（15）+渠道号（8）+外部交易码（15）
            String area=getBankConfig().getValueAsString("area");
            String businessTypes=getBankConfig().getValueAsString("businessTypes");
            String entrustmentUnit=getBankConfig().getValueAsString("entrustmentUnit");
            String businessUnit=getBankConfig().getValueAsString("businessUnit");
            String channelNumber=getBankConfig().getValueAsString("channelNumber");
            sbContent.append(String.format("%-4s", area));//地区码
            sbContent.append(String.format("%-6s", businessTypes));//业务种类

            sbContent.append(String.format(tmpFifteen, entrustmentUnit));//委托单位
            sbContent.append(String.format(tmpFifteen, businessUnit));//业务单位
            sbContent.append(String.format("%-8s", channelNumber));//渠道号
            sbContent.append(String.format(tmpFifteen, "ZLDS001"));
            String tmpStrPlain = xmlWriter.toXmlString();
            String result=sbContent.toString();
            String sendMessage=result+tmpStrPlain;
            String[] tmpRetStr = sendToBank(sendMessage);
            if(tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ROOT/respinfo");
                    String tmpRespCode = tmpBkReader.getFirstText("/ROOT/respcode");
                    tmpRetDetail.transState = tmpRespCode;
                    tmpRetDetail.payInfoCode = tmpRespCode;
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req9144);
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
            if (actItem == null ) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号:[" + p_req9144.recAct + "]商户配置信息!";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
            xmlWriter.writeStartElement("ROOT");
            xmlWriter.writeElementString("trancode", "ZLDS003");
            xmlWriter.writeElementString("sndseqno", getQryTransID());
            xmlWriter.writeElementString("mccprtcno", actItem.appId);
            xmlWriter.writeElementString("orgseqno", p_req9144.askNumber);
            xmlWriter.writeElementString("trandt", Format.Date10Format.format(p_req9144.getBgnDateTime()));
            xmlWriter.writeEndElement();
            StringBuilder sbContent=new StringBuilder();
            //报文长度（8）+地区码（4）+业务种类（6）+委托单位（15）+业务单位（15）+渠道号（8）+外部交易码（15）
            String area=getBankConfig().getValueAsString("area");
            String businessTypes=getBankConfig().getValueAsString("businessTypes");
            String entrustmentUnit=getBankConfig().getValueAsString("entrustmentUnit");
            String businessUnit=getBankConfig().getValueAsString("businessUnit");
            String channelNumber=getBankConfig().getValueAsString("channelNumber");
            sbContent.append(String.format("%-4s", area));//地区码
            sbContent.append(String.format("%-6s", businessTypes));//业务种类
            sbContent.append(String.format(tmpFifteen, entrustmentUnit));//委托单位
            sbContent.append(String.format(tmpFifteen, businessUnit));//业务单位
            sbContent.append(String.format("%-8s", channelNumber));//渠道号
            sbContent.append(String.format(tmpFifteen, "ZLDS003"));
            String tmpStrPlain = xmlWriter.toXmlString();
            String result=sbContent.toString();
            String sendMessage=result+tmpStrPlain;
            String[] tmpRetStr = sendToBank(sendMessage);
            if(tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ROOT/respinfo");
                    String tmpRespCode = tmpBkReader.getFirstText("/ROOT/respcode");
                    tmpRetDetail.transState = tmpRespCode;
                    tmpRetDetail.payInfoCode = tmpRespCode;
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}
